package com.hadoop.mapreduce.phoneFlowSort;

import com.hadoop.mapreduce.phoneProvince.FlowBean;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * 将手机号 按照总流量排名排序
 */
public class PhoneFlowSort {
    static class PhoneFlowSortMapper extends Mapper<IntWritable, Text, FlowBean, Text> {
        private Text text=new Text();
        private FlowBean flowBean=new FlowBean();
        @Override
        protected void map(IntWritable key, Text value, Context context) throws IOException, InterruptedException {
            String[] strings = value.toString().split("\t");
            String phone = strings[1];
            long sumFlow = Long.parseLong(strings[strings.length - 1]);

            flowBean.setSumFlow(sumFlow);
            text.set(phone);
            context.write(flowBean,text);
        }
    }

    static class PhoneFlowSortReducer extends Reducer< FlowBean,Text, Text, FlowBean> {
        private FlowBean flowBean=new FlowBean();
        @Override
        protected void reduce(FlowBean key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            context.write(values.iterator().next(),key);
        }
    }


    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        Configuration config=new Configuration();
        /*conf.set("mapreduce.framework.name", "yarn");
		conf.set("yarn.resoucemanager.hostname", "mini1");*/
        Job job=Job.getInstance(config);

        //指定本程序的jar包所在的本地路径
        job.setJarByClass(PhoneFlowSort.class);

        //指定本业务job要使用的mapper/Reducer业务类
        job.setMapOutputValueClass(PhoneFlowSortMapper.class);
        job.setOutputValueClass(PhoneFlowSortReducer.class);

        //指定mapper输出数据的kv类型
        job.setMapOutputValueClass(FlowBean.class);
        job.setMapOutputValueClass(Text.class);

        //指定最终输出的数据的kv类型
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(FlowBean.class);

        //指定job的输入原始文件所在目录
        FileInputFormat.setInputPaths(job,new Path(args[0]));

        Path path = new Path(args[1]);
        FileSystem fileSystem = FileSystem.get(config);
        if(fileSystem.exists(path))
            fileSystem.delete(path,true);
        //指定job的输出结果所在目录
        FileOutputFormat.setOutputPath(job,path);

        //将job中配置的相关参数，以及job所用的java类所在的jar包，提交给yarn去运行
        /*job.submit();*/
        boolean res = job.waitForCompletion(true);
        System.exit(res?0:1);
    }
}
